package cn.iocoder.yudao.module.engine.controller.app.message;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.engine.controller.app.message.vo.AppMessagePageReqVO;
import cn.iocoder.yudao.module.engine.controller.app.message.vo.AppMessageRespVO;
import cn.iocoder.yudao.module.engine.service.core.aichat.IAIChatService;
import cn.iocoder.yudao.module.infra.util.TraceIdUtil;
import cn.iocoder.yudao.module.resource.api.IMessageApi;
import cn.iocoder.yudao.module.resource.api.model.message.MessageDTO;
import cn.iocoder.yudao.module.resource.api.model.message.MessagePageReqDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 APP - 消息")
@RestController
@RequestMapping("/lm/message")
@Validated
@Slf4j
public class AppMessageController {
    private final static long SSE_TIMEOUT_MS = 1000 * 60 * 5;

    @Resource
    private IMessageApi messageApi;
    @Resource
    private IAIChatService chatService;

    @GetMapping(value = "/create", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "创建消息")
    @PreAuthenticated
    public ResponseBodyEmitter createMessageByGet(@RequestParam("sessionId") Long sessionId,
                                                  @RequestParam(value = "text") String textFromUser,
                                                  @RequestParam(value = "returnAudio", required = false, defaultValue = "true") Boolean returnAudio,
                                                  @RequestParam(value = "returnAudioFormat", required = false, defaultValue = "mp3") String returnAudioFormat) {
        final ResponseBodyEmitter emitter = createSseEmitter(TraceIdUtil.getTraceId(), true);
        final Long loginUserId = getLoginUserId();
        //chatService.createMessage(IdUtil.objectId(), new EmitterILLMChatClient(emitter), loginUserId, sessionId, IdUtil.objectId(), textFromUser, null, returnAudio, returnAudioFormat);
        log.info("先返回emitter");
        return emitter;
    }

    @GetMapping(value = "/create-ndjson", produces = MediaType.APPLICATION_NDJSON_VALUE)
    @Operation(summary = "创建消息")
    @PreAuthenticated
    public ResponseEntity<ResponseBodyEmitter> createMessageByPost(@RequestParam("sessionId") Long sessionId,
                                                                   @RequestParam(value = "text") String textFromUser,
                                                                   @RequestParam(value = "returnAudio", required = false, defaultValue = "true") Boolean returnAudio,
                                                                   @RequestParam(value = "returnAudioFormat", required = false, defaultValue = "mp3") String returnAudioFormat) {
        final ResponseBodyEmitter emitter = createSseEmitter(TraceIdUtil.getTraceId(), false);
        final Long loginUserId = getLoginUserId();
       // chatService.createMessage(IdUtil.objectId(), new NSJsonILLMChatClient(emitter), loginUserId, sessionId, IdUtil.objectId(), textFromUser, null, returnAudio, returnAudioFormat);
        return ResponseEntity.ok()
                .header("Content-Type", MediaType.APPLICATION_NDJSON_VALUE)
                .body(emitter);
    }

    @NotNull
    private ResponseBodyEmitter createSseEmitter(String traceId, boolean eventStream) {
        ResponseBodyEmitter emitter = eventStream ? new SseEmitter(SSE_TIMEOUT_MS) : new ResponseBodyEmitter(SSE_TIMEOUT_MS);
        emitter.onTimeout(() -> log.warn("SseEmitter超时，traceId: {}", traceId));
        emitter.onError((ex) -> log.error(StrUtil.format("SseEmitter发生错误, traceId = {}", traceId), ex));
        emitter.onCompletion(() -> log.info("SseEmitter完成，traceId: {}", traceId));
        return emitter;
    }

    @GetMapping("/page")
    @Operation(summary = "获得消息分页")
    @PreAuthenticated
    public CommonResult<PageResult<AppMessageRespVO>> getMessagePage(@Valid AppMessagePageReqVO pageReqVO) {
        final Long loginUserId = getLoginUserId();
        PageResult<MessageDTO> pageResult = messageApi.getMessagePageByUserId(loginUserId, BeanUtils.toBean(pageReqVO, MessagePageReqDTO.class));
        return success(BeanUtils.toBean(pageResult, AppMessageRespVO.class));
    }

    @GetMapping("/get")
    @Operation(summary = "获得消息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthenticated
    public CommonResult<AppMessageRespVO> getMessage(@RequestParam("id") String id) {
        final Long loginUserId = getLoginUserId();
        MessageDTO message = messageApi.getMessageByUserId(loginUserId, id);
        return success(BeanUtils.toBean(message, AppMessageRespVO.class));
    }

}